package com.baizhi.controller;

import com.baizhi.entity.Admin;
import com.baizhi.entity.Student;
import com.baizhi.entity.Teacher;
import com.baizhi.service.IAdminService;
import com.baizhi.service.IStudentService;
import com.baizhi.service.ITeacherService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IAdminService as;
    @Autowired
    private ITeacherService ts;
    @Autowired
    private IStudentService ss;
    @GetMapping("/login")
    public boolean login(String name, String pwd, int role, HttpSession session){
        Object one=null;
        if(role==1){
            QueryWrapper<Student> wrapper=new QueryWrapper<>();
            wrapper.eq("name",name).eq("pwd",pwd);
             one = ss.getOne(wrapper);
        }
        if(role==2){
            QueryWrapper<Teacher> wrapper=new QueryWrapper<>();
            wrapper.eq("name",name).eq("pwd",pwd);
             one = ts.getOne(wrapper);
        }
        if(role==3){
            QueryWrapper<Admin> wrapper=new QueryWrapper<>();
            wrapper.eq("name",name).eq("pwd",pwd);
             one = as.getOne(wrapper);
        }
        if(one!=null){
            session.setAttribute("user",one);
        }
        return one!=null;
    }
    @GetMapping("/logout")
    public void logout(HttpSession session){
        session.invalidate();
    }

    //修改用户的密码
    @PutMapping("/updatePwd")
    public void updatePwd(int role,String pwd,HttpSession session){
        if(role==1){
            Student stu=(Student)session.getAttribute("user");
            stu.setPwd(pwd);
            ss.updateById(stu);
            session.setAttribute("user",stu);
        }
        if(role==2){
            Teacher tea=(Teacher)session.getAttribute("user");
            tea.setPwd(pwd);
            ts.updateById(tea);

            session.setAttribute("user",tea);
        }
        if(role==3){
            Admin admin=(Admin)session.getAttribute("user");
            admin.setPwd(pwd);
            as.updateById(admin);

            session.setAttribute("user",admin);
        }
    }
}
